_ = require 'underscore'
ViewContentHandler = require '../helpers/view_content_handler'
HttpHandler = require '../../../helpers/http_handler'
ViewDataHandler = require '../models/view_data_handler'

comodityHandler = 
  commodityPageHandler : (req, res, next) ->
    id = req.params.id
    ViewDataHandler.commodity id, (err, data) ->
      if err
        res.render 'error', 504
      else
        view = 'ys/commodity'
        renderData = ViewContentHandler.commodity req, view, '每天浏览一下，关注更多的新产品！', -1, data[0]
        HttpHandler.renderAndCache req, res, view, renderData

  commodityModifyPageHandler : (req, res, next) ->
    id = req.params.id
    ViewDataHandler.commodity id, (err, data) ->
      console.dir data
      if err
        res.render 'error', 504
      else
        view = 'ys/commodity_modify'
        renderData = ViewContentHandler.commodityModify req, view, '每天浏览一下，关注更多的新产品！', -1, data[0]
        HttpHandler.renderAndCache req, res, view, renderData


  saveCommodityHandler : (req, res, next) ->
    data = req.body
    id = data._id
    delete data._id
    data.modifiedTime = new Date()
    data.price = data.price || 0
    console.dir data
    ViewDataHandler.commodityModify id, data, (err, data) ->
      console.log "err:#{err}"
      if err
        data = 
          code : 1000
          msg : err.toString()
      else
        data = 
          code : 0
          msg : 'success'
      res.send JSON.stringify data

  table : (req, res, next) ->
    view = 'ys/commodity_table_view'
    ViewDataHandler.table (err, data) ->
      if err
        res.render 'error', 504
      else
        docs = []
        _.each data, (item) ->
          pickItem = 
            id : item.barcode
            cell : _.pick item, 'barcode', 'title', 'specification'
          docs.push pickItem
        if req.xhr
          responData =
            page : 1
            total : docs.length
            rows : docs
          res.json responData
        else
          renderData = ViewContentHandler.table req, view, '每天浏览一下，关注更多的新产品！', 3, docs
          HttpHandler.renderAndCache req, res, view, renderData
module.exports = comodityHandler